import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

class S3Controller {
  static const String SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb";
  static const String CHARACTERISTIC_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb";

  BluetoothDevice? _device;
  BluetoothCharacteristic? _characteristic;
  StreamSubscription<List<int>>? _subscription;

  // 手柄按键事件回调
  Function(Map<String, dynamic>)? onButtonPressed;

  // 扫描S3手柄设备
  Future<List<BluetoothDevice>> scanDevices() async {
    List<BluetoothDevice> devices = [];
    try {
      FlutterBluePlus.startScan(timeout: Duration(seconds: 10));

      FlutterBluePlus.scanResults.listen((data) {
        print("=========");
      });
      // await for (ScanResult result in FlutterBluePlus.scanResults) {
      //   if (result.device.name.contains("S3") || result.device.name.contains("GamePad")) {
      //     devices.add(result.device);
      //   }
      // }

      FlutterBluePlus.stopScan();
    } catch (e) {
      print("扫描错误: $e");
    }
    return devices;
  }

  // 连接到指定手柄
  Future<bool> connect(BluetoothDevice device) async {
    try {
      await device.connect(timeout: Duration(seconds: 15));
      _device = device;

      // 发现服务和特征
      List<BluetoothService> services = await device.discoverServices();
      for (BluetoothService service in services) {
        if (service.uuid.toString().toLowerCase() == SERVICE_UUID) {
          for (BluetoothCharacteristic c in service.characteristics) {
            if (c.uuid.toString().toLowerCase() == CHARACTERISTIC_UUID) {
              _characteristic = c;

              // 启用通知
              await c.setNotifyValue(true);

              // 监听手柄数据
              _subscription = c.value.listen((value) {
                _handleData(value);
              });

              return true;
            }
          }
        }
      }
      return false;
    } catch (e) {
      print("连接错误: $e");
      disconnect();
      return false;
    }
  }

  // 断开连接
  void disconnect() {
    _subscription?.cancel();
    _device?.disconnect();
    _device = null;
    _characteristic = null;
  }

  // 发送命令到手柄
  Future<void> sendCommand(List<int> data) async {
    if (_characteristic == null) return;

    try {
      await _characteristic!.write(data, withoutResponse: true);
    } catch (e) {
      print("发送命令错误: $e");
    }
  }

  // 处理手柄数据
  void _handleData(List<int> data) {
    if (data.length < 5) return;

    // 解析按键数据 - 示例格式，实际协议需根据手柄规格调整
    Map<String, dynamic> buttonStates = {
      'a': (data[2] & 0x01) != 0,
      'b': (data[2] & 0x02) != 0,
      'x': (data[2] & 0x04) != 0,
      'y': (data[2] & 0x08) != 0,
      'l1': (data[2] & 0x10) != 0,
      'r1': (data[2] & 0x20) != 0,
      'select': (data[2] & 0x40) != 0,
      'start': (data[2] & 0x80) != 0,
    };

    // 解析摇杆数据
    Map<String, int> joystick = {
      'leftX': data[3],
      'leftY': data[4],
      'rightX': data.length > 5 ? data[5] : 128,
      'rightY': data.length > 6 ? data[6] : 128,
    };

    // 触发回调
    onButtonPressed?.call({
      'buttons': buttonStates,
      'joystick': joystick,
      'rawData': data,
    });
  }
}
